package com.jr.filter;

import com.alibaba.fastjson.JSON;
import com.jr.util.Message;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Function：
 * @Author 梁明哲
 * @Email 424577090@qq.com
 * @Package com.jr.filter
 * @Project InvoiceManage
 * @Date 2023-02-20 10:26:06
 */
//@WebFilter("/admin/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        PrintWriter out = servletResponse.getWriter();
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 准备一个白名单，哪些请求放行！！！
        List<String> urls = Arrays.asList(
                "/InvoiceManage/admin/login.do",
                "/InvoiceManage/admin/updateBaseData.bd"
        );
        // 获取请求的uri地址
        String uri = request.getRequestURI();
        //System.out.println("filter:" + uri);
        if(urls.contains(uri)) {
            // 如果我们的请求路径是白名单里的，放行
            chain.doFilter(request,response);
            return;
        }
        Object users = request.getSession().getAttribute("users");
        if(Objects.isNull(users)) {
            // 说明没有登录
//            response.sendRedirect("../pages/login.html");
            // 返回json串,从前台跳
            out.write(JSON.toJSONString(new Message(999,"请登录!")));
            return;
        }
        chain.doFilter(request,response);
    }
}







